<?php
declare (strict_types = 1);

namespace app\command;

use app\common\model\ContentReadModel;
use app\common\model\MoneyCashModel;
use app\common\model\MoneyRecordModel;
use app\common\RootCommand;
use app\common\service\PayService;
use think\console\Input;
use think\console\Output;

class ArticleReadCensus extends RootCommand
{
    /**
     * 配置指令
     */
    protected function configure()
    {
        // redis缓存客户端
        $this->taskHashClient = (new \redis\TaskHash());
        // 指令配置
        $this->setName('articleReadCensus')
            ->setDescription('统计用户阅读数');
    }

    /**
     * 执行指令
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     */
    protected function execute(Input $input, Output $output)
    {
        try {
            // 统计日期
            $today = date('Y-m-d');
            // 筛选条件
            $where = ['write_date' => $today, 'method' => MONEY_RECORD_METHOD_READ];
            // 用户ID
            if ($memberIds = MoneyRecordModel::where($where)->group(['member_id'])->column('member_id')) {
                $memberIds = array_chunk($memberIds, 1000);
                foreach ($memberIds as $rows) {
                    $readData = [];
                    $createTime = date('Y-m-d H:i:s');
                    foreach ($rows as $memberId) {
                        // 读取文章缓存数据
                        $article = $this->articleData($memberId, 'article');
                        // 用户阅读数据
                        $readData[] = ['member_id' => $memberId, 'content_ids' => json_encode($article['view']),
                            'write_date' => $today, 'quantity' => $article['qty'], 'create_time' => $createTime,
                            'seven_minute' => $article['invite']['minute'] ? 1 : 0];
                    }
                    // 保存数据
                    empty($readData) || (new ContentReadModel())->insertAll($readData);
                }
            }
            echo '更新成功：' . date('Y-m-d H:i:s') . "\n";
            $this->sendTxtNotify('文章统计更新成功【' . date('Y-m-d H:i:s') . '】');
        } catch (\Exception $e) {
            // 钉钉通知
            $this->sendTxtNotify('文章统计异常【' . date('Y-m-d H:i:s') . '】：' . $e->getMessage());
        }
    }

    /**
     * 批量转账
     * @throws \app\common\RootException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function batchTransfer()
    {
        // 筛选字段
        $fields = ['mc.id', 'mc.state', 'm.invite'];
        // 处理时间
        $betweenDate = ['2022-05-10', date('Y-m-d H:i:s', strtotime('-6hour'))];
        // 筛选条件
        $where = [['mc.state', '=', 2], ['m.state', '=', 0], ['mc.create', 'between', $betweenDate]];
        // 数据处理
        MoneyCashModel::alias('mc')->join(['sys_member' => 'm'], 'mc.member_id = m.id', 'left')->where($where)
            ->field($fields)->chunk(100, function ($rows) {
                foreach ($rows as $row) {
                    $row->state = 1;
                    $row->save();
                    (new PayService())->cashPay($row['id']);
                    sleep(1);// 等待1秒
                    echo "订单ID：【{$row['id']}】 - 用户【{$row['invite']}】处理完成\n";
                }
            });
    }

    /**
     * 提现失败
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function batchTransferFail()
    {
        // 筛选字段
        $fields = ['mc.id', 'mc.state', 'm.invite'];
        // 处理时间
        $betweenDate = ['2022-05-10', date('Y-m-d H:i:s', strtotime('-6hour'))];
        // 筛选条件
        $where = [['mc.state', '=', 2], ['m.state', '=', 0], ['mc.create_time', 'between', $betweenDate]];
        // 数据处理
        MoneyCashModel::alias('mc')->join(['sys_member' => 'm'], 'mc.member_id = m.id', 'left')->where($where)
            ->field($fields)->chunk(100, function ($rows) {
                foreach ($rows as $row) {
                    $row->remark = '提现一直未收到响应';
                    $row->save();
                    (new PayService())->cashFailed($row['id']);
                    sleep(1);// 等待1秒
                    echo "订单ID：【{$row['id']}】 - 用户【{$row['invite']}】处理完成\n";
                }
            });
    }

    /**
     * 文章阅读数据
     * @param int $memberId
     * @param string $field
     * @return array|int|mixed
     */
    protected function articleData(int $memberId, string $field = '')
    {
        // 读取缓存
        $articleData = $this->taskHashClient->taskHash($memberId, 'article');
        // 数据处理
        if (empty($articleData) || !$this->hashToday($articleData)) {
            $today = date('Y-m-d');
            // 数据初始化
            $articleData = ['qty' => 0, 'date' => $today, 'read' => $articleData['read'] ?? 0, 'view' => [],
                'invite' => ['day' => $articleData['invite']['day'] ?? 0, 'date' => $articleData['invite']['date'] ?? $today,
                    'minute' => false, 'today' => false]];
            // 天数断开重置（邀请任务第三阶段奖励，天数连续3天）
            if (!in_array($articleData['invite']['date'], [$today, date('Y-m-d', strtotime('-1day'))])) {
                $articleData['invite']['day'] = 0;
                $articleData['invite']['date'] = $today;
            }
        }
        return $articleData[$field] ?? $articleData;
    }
}
